package com.wxh.bomb.netty.thread.thread.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class MyFile {
	// 文件
	private File file;
	// 当前文件的索引
	public AtomicInteger index;
	// 线程锁
	private ReentrantLock lock = new ReentrantLock();
	
	//初始化
	public MyFile(File file, int index){
		this.file = file;
		this.index = new AtomicInteger(index);
	}
	
	// 将字符写入文件
	public void writeStr(String content) throws FileNotFoundException{
		// 文件输出流
		FileWriter out = null;
		BufferedWriter bw = null;
		try {
			lock.lockInterruptibly();
			out = new FileWriter(file);
			bw = new BufferedWriter(out);
			out.write(content);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();// 关闭文件输出流
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public String readStr() throws FileNotFoundException{
		StringBuilder sb = new StringBuilder();
		FileReader in = null;
		BufferedReader br = null;
		try {
			 in = new FileReader(file);
			 br = new BufferedReader(in);
			 sb.append(br.readLine());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();// 关闭文件输出流
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
}
